package com.flyxiaozhu.erp.core.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * OSS工具类
 */

public class OSSClientUtils {
    // 本地异常日志
    public static final Logger logger = LoggerFactory.getLogger(OSSClientUtils.class);


    // 存储空间
    private String bucketName;

    // 文件存储目录
    private String fileDir;

    private OSSClient ossClient;

    public OSSClientUtils(String endpoint, String accessKeyId, String accessKeySecret, String bucketName, String fileDir) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        this.bucketName = bucketName;
        this.fileDir = fileDir;
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url 图片上传路径
     */
    public void uploadImg2OSS(String url) {
        File file = new File(url);
        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(file);
            String[] split = url.split("/");
            this.uploadFile2OSS(fileInputStream, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            logger.error("图片上传失败：" + e.getMessage());
        }
    }


    public String uploadImg2Oss(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
        } catch (Exception e) {
            logger.error("图片上传失败：" + e.getMessage());
        }
        return name;
    }

    /**
     * 上传到OSS服务器，如果同名文件或覆盖
     *
     * @param inputStream 文件流
     * @param filename    文件名称，包括后缀
     * @return 出错返回 "" ，正确返回MD5数字签名
     */
    private String uploadFile2OSS(InputStream inputStream, String filename) {
        String ret = "";
        try {
            // 创建上传的Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();

            // 上传的文件的长度
            objectMetadata.setContentLength(inputStream.available());
            // 指定该Object被下载时的网页的缓存行为
            objectMetadata.setCacheControl("not-cache");
            // 指定该Object下设置Header
            objectMetadata.setHeader("Pragma", "no-cache");
            //指定该Object被下载时的内容编码格式
            objectMetadata.setContentEncoding("utf-8");
            //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            //如果没有扩展名则填默认值application/octet-stream
            objectMetadata.setContentType(getContentType(filename.substring(filename.lastIndexOf("."))));
            //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            objectMetadata.setContentDisposition("inline;filename=" + filename);

            // 上传文件
            PutObjectResult putObjectRequest = ossClient.putObject(bucketName, fileDir + filename, inputStream, objectMetadata);
            // 解析结果
            ret = putObjectRequest.getETag();
        } catch (IOException e) {
            logger.error("IO异常：" + e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 判断OSS服务文件上传时文件的contentType
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    private static String getContentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {

        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.fileDir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    private String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            //        图片私有的直接返回
//            return url.toString().split("\\?")[0];
            return url.toString();
        }
        return null;
    }
}
